package com.flame.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public final class ZipUtils {

    private ZipUtils() {
    }

    /**
     * dir or file toZip
     *
     * @param zipFileName 生成的zipFileName
     * @param location    dir or file 的路径
     * @param flag        生成完是否删除源文件
     * @return
     */
    public static String toZip(String zipFileName, String location, boolean flag) throws IOException {
        try {
            String zipLocation = System.getProperty("java.io.tmpdir") + File.separator + "flame" + File.separator + zipFileName;
            File sourceFile = new File(location);
            File zip = new File(zipLocation);
            if (!zip.getParentFile().exists()) {
                zip.getParentFile().mkdirs();
            }
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zip));
            zip(zipOutputStream, sourceFile, "");
            zipOutputStream.flush();
            zipOutputStream.close();
            if (flag) {
                FileUtils.delete(sourceFile);
            }
            return zipLocation;
        } catch (IOException e) {
            throw e;
        }
    }

    private static void zip(ZipOutputStream zipOutputStream, File file, String filePath) throws IOException {
        if (filePath.length() != 0) {
            filePath = filePath + "/" + file.getName();
        } else {
            filePath = file.getName();
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null || files.length == 0) {
                zipOutputStream.putNextEntry(new ZipEntry(filePath));
                zipOutputStream.closeEntry();
            } else {
                for (File f : files) {
                    zip(zipOutputStream, f, filePath);
                }
            }
        } else {
            zipOutputStream.putNextEntry(new ZipEntry(filePath));
            FileInputStream inputStream = new FileInputStream(file);
            int len;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf)) != -1) {
                zipOutputStream.write(buf, 0, len);
            }
            inputStream.close();
            zipOutputStream.closeEntry();
        }
    }
}
